import express from "express"
import path from "path"
import fs from "fs"
import uuid from "node-uuid"
let PublicUser = path.join(__dirname,"./public")
let app = express()
app.listen(3000,()=>{
    console.log("服务器启动")})
    //登录拦截
    app.get("/hom.html",(req,res,next)=>{
        //获取cook
        let cook = req.get("Cookie")|| ""
        let brr  =   cook.split ("; ")
        let obj = {}
        brr.forEach(item => {
            obj[item.slice(0,item.indexOf("="))]=item.slice(item.indexOf("=")+1)
        });
        let ck = obj["cook"]|| null
        //获取 服务器 cook 
        let arr = JSON.parse(fs.readFileSync(path.join(__dirname,"./public/cook.json")))
        let is = arr.find(item =>{return item === ck })
        if (is) {
            next()
        }else{
            res.redirect("./login.html")
        }
    })
//访问静态资源
app.use(
    express.static(PublicUser)
)
//get 请求·
app.get("/login",(req,res,next)=>{
 let {user, pass} = req.query
 console.log(user);
 console.log(pass);
 let arr = JSON.parse(fs.readFileSync(path.join(__dirname,"./public/user.json")))
 let is = arr.find(item =>{return item.user === user })
 if (is) {
        if (is.pass === pass) {
            let str = uuid.v1()
            let arr = JSON.parse(fs.readFileSync(path.join(__dirname,"./public/cook.json")))
            arr.push(str)
            fs.writeFileSync(path.join(__dirname,"./public/cook.json"),JSON.stringify(arr),"utf-8")
           res.cookie("cook",str)
           res.send("001")      
        }else{
            res.send("002")      
        }
 }else{
    res.send("003")      
 }
})
//post 请求参数
app.use(
    express.json()
)
//post 请求
app.post("/zhu",(req,res,next)=>{

})